package com.qumoyugo.springframework.beans.factory.xml;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.qumoyugo.springframework.beans.BeansException;
import com.qumoyugo.springframework.beans.PropertyValue;
import com.qumoyugo.springframework.core.io.Resource;
import com.qumoyugo.springframework.core.io.ResourceLoader;
import com.qumoyugo.springframework.beans.factory.config.BeanDefinition;
import com.qumoyugo.springframework.beans.factory.config.BeanReference;
import com.qumoyugo.springframework.beans.factory.support.AbstractBeanDefinitionReader;
import com.qumoyugo.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Cedric
 * @date 2021/11/22 16:07
 * @description 解析XML处理Bean注册
 */
public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {

    public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) {
        super(registry);
    }

    public XmlBeanDefinitionReader(BeanDefinitionRegistry registry, ResourceLoader resourceLoader) {
        super(registry, resourceLoader);
    }

    @Override
    public void loadBeanDefinitions(Resource resource) throws BeansException {
        try {
            try (InputStream inputStream = resource.getInputStream()) {
                doLoadBeanDefinitions(inputStream);
            }
        } catch (IOException | ClassNotFoundException e) {
            throw new BeansException("IOException parse XML document from " + resource, e);
        }
    }

    @Override
    public void loadBeanDefinitions(Resource... resources) throws BeansException {
        for (Resource resource : resources) {
            loadBeanDefinitions(resource);
        }
    }

    @Override
    public void loadBeanDefinitions(String location) throws BeansException {
        ResourceLoader resourceLoader = getResourceLoader();
        Resource resource = resourceLoader.getResource(location);
        loadBeanDefinitions(resource);
    }

    @Override
    public void loadBeanDefinitions(String[] locations) throws BeansException {
        for (String location : locations) {
            ResourceLoader resourceLoader = getResourceLoader();
            Resource resource = resourceLoader.getResource(location);
            loadBeanDefinitions(resource);
        }
    }

    protected void doLoadBeanDefinitions(InputStream inputStream) throws ClassNotFoundException {
        Document doc = XmlUtil.readXML(inputStream);
        Element root = doc.getDocumentElement();
        NodeList childNodes = root.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {

            // 不是元素
            if (!(childNodes.item(i) instanceof Element)) {
                continue;
            }
            // 不是对象
            if (!("bean").equals(childNodes.item(i).getNodeName())) {
                continue;
            }

            // 解析标签
            Element bean = (Element)childNodes.item(i);
            String id = bean.getAttribute("id");
            String name = bean.getAttribute("name");
            String className = bean.getAttribute("class");
            String initDataMethod = bean.getAttribute("init-method");
            String destroyDataMethod = bean.getAttribute("destroy-method");

            // 获取Class，方便获取类中的名称
            Class<?> clazz = Class.forName(className);

            // id优先于name
            String beanName = StrUtil.isNotEmpty(id) ? id : name;
            if (StrUtil.isEmpty(beanName)) {
                beanName = StrUtil.lowerFirst(clazz.getSimpleName());
            }

            // 定义Bean
            BeanDefinition beanDefinition = new BeanDefinition(clazz);
            beanDefinition.setInitMethodName(initDataMethod);
            beanDefinition.setDestroyMethodName(destroyDataMethod);

            //设置属性并填充
            for(int j = 0; j < bean.getChildNodes().getLength(); j++) {
                if (!(bean.getChildNodes().item(j) instanceof Element)) {
                    continue;
                }
                if (!("property".equals(bean.getChildNodes().item(j).getNodeName()))) {
                    continue;
                }

                // 解析表情property
                Element property = (Element)bean.getChildNodes().item(j);
                String attrName = property.getAttribute("name");
                String attrValue = property.getAttribute("value");
                String attrRef = property.getAttribute("ref");
                // 获取属性值：引用对象和值对象
                Object value = StrUtil.isNotEmpty(attrRef) ? new BeanReference(attrRef) : attrValue;
                beanDefinition.getPropertyValues().addPropertyValue(new PropertyValue(attrName, value));
            }

            if (getRegistry().containBeanDefinition(beanName)) {
                throw new BeansException("Duplicated beanName [" + beanName + "] is not allowed.");
            }

            //注册bean
            getRegistry().registerBeanDefinition(beanName, beanDefinition);
        }
    }
}
